<template>
  <div class="user-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="toolbar">
        <div class="left">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon> 新增
          </el-button>
          <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon> 批量删除
          </el-button>
          <el-button @click="handleExport">
            <el-icon><Download /></el-icon> 导出
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="realName" label="真实姓名" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip />
        <el-table-column prop="roleName" label="角色" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
              {{ scope.row.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button link type="primary" size="small" @click="handleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                link
                :type="scope.row.status === '1' ? 'danger' : 'success'"
                size="small"
                @click="handleToggleStatus(scope.row)"
              >
                {{ scope.row.status === '1' ? '禁用' : '启用' }}
              </el-button>
              <el-button link type="danger" size="small" @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
      destroy-on-close
    >
      <el-form ref="userFormRef" :model="userForm" :rules="userRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userForm.roleId" placeholder="请选择角色">
            <el-option
              v-for="role in roleOptions"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="userForm.status">
            <el-radio value="1">启用</el-radio>
            <el-radio value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Plus, Delete, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  username: '',
  phone: '',
  status: '',
  createTime: null,
})

// 表格数据
const loading = ref(false)
const tableData = ref([
  {
    id: '1',
    username: 'admin',
    realName: '系统管理员',
    phone: '13800138000',
    email: 'admin@example.com',
    roleId: '1',
    roleName: '超级管理员',
    status: '1',
    createTime: '2023-01-01 12:00:00',
  },
  {
    id: '2',
    username: 'operator',
    realName: '运营人员',
    phone: '13800138001',
    email: 'operator@example.com',
    roleId: '2',
    roleName: '运营人员',
    status: '1',
    createTime: '2023-01-02 10:00:00',
  },
  {
    id: '3',
    username: 'test',
    realName: '测试用户',
    phone: '13800138002',
    email: 'test@example.com',
    roleId: '3',
    roleName: '普通用户',
    status: '0',
    createTime: '2023-01-03 09:00:00',
  },
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 选中行
const selectedRows = ref([])

// 用户表单
const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 edit
const userFormRef = ref(null)
const userForm = reactive({
  id: '',
  username: '',
  realName: '',
  password: '',
  phone: '',
  email: '',
  roleId: '',
  status: '1',
})
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change'],
    },
  ],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
}

// 角色选项
const roleOptions = [
  { id: '1', name: '超级管理员' },
  { id: '2', name: '运营人员' },
  { id: '3', name: '普通用户' },
  { id: '4', name: '测试人员' },
]

// 搜索方法
const handleSearch = () => {
  loading.value = true
  // 实际应该调用API接口，这里模拟一下
  setTimeout(() => {
    loading.value = false
    ElMessage.success('搜索成功')
  }, 500)
}

// 重置搜索
const resetSearch = () => {
  searchForm.username = ''
  searchForm.phone = ''
  searchForm.status = ''
  searchForm.createTime = null
  handleSearch()
}

// 选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

// 分页当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 打开新增对话框
const handleAdd = () => {
  dialogType.value = 'add'
  userForm.id = ''
  userForm.username = ''
  userForm.realName = ''
  userForm.password = ''
  userForm.phone = ''
  userForm.email = ''
  userForm.roleId = ''
  userForm.status = '1'
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  dialogType.value = 'edit'
  userForm.id = row.id
  userForm.username = row.username
  userForm.realName = row.realName
  userForm.password = ''
  userForm.phone = row.phone
  userForm.email = row.email
  userForm.roleId = row.roleId
  userForm.status = row.status
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return
  try {
    await userFormRef.value.validate()
    loading.value = true
    // 实际应该调用API接口，这里模拟一下
    setTimeout(() => {
      loading.value = false
      dialogVisible.value = false
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功')
      handleSearch()
    }, 500)
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 切换状态
const handleToggleStatus = (row) => {
  const action = row.status === '1' ? '禁用' : '启用'
  ElMessageBox.confirm(`确定要${action}用户 ${row.username} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 切换状态的逻辑
      row.status = row.status === '1' ? '0' : '1'
      ElMessage.success(`${action}成功`)
    })
    .catch(() => {})
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除用户 ${row.username} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 删除用户的逻辑
      ElMessage.success('删除成功')
      handleSearch()
    })
    .catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 批量删除的逻辑
      ElMessage.success('批量删除成功')
      handleSearch()
    })
    .catch(() => {})
}

// 导出用户
const handleExport = () => {
  ElMessage.success('导出成功')
}
</script>

<style scoped>
.user-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.search-card,
.table-card {
  margin-bottom: 0;
  transition: all 0.3s;
  border-radius: var(--el-card-border-radius);
  overflow: hidden;
  box-shadow: var(--box-shadow-base);
  border: none;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.operation-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.operation-buttons .el-button {
  font-weight: 500;
  padding: 6px 10px;
  border-radius: 4px;
}

/* Element Plus 样式覆盖 */
:deep(.el-card__header) {
  padding: var(--el-card-header-padding);
  border-bottom: 1px solid var(--border-color-lighter);
}

:deep(.el-date-table td.current:not(.disabled) .el-date-table-cell__text) {
  color: #fff;
}
</style>
